﻿using System;
using System.Text;
using System.Web.Security;
using MySql.Data.MySqlClient;
using log4net;
using System.Web;
using System.Security.Cryptography;
using System.Web.Configuration;

namespace Possan.MySQL.Providers
{
	public class Membership : MembershipProvider
	{
		public override string ApplicationName
		{
			get
			{
				_log.Debug("get ApplicationName (" + _name + ")");
				return _name;
			}
			set
			{
				_log.Debug("set ApplicationName=" + value);
				_name = value;
			}
		}

		private string _connName;
		private string _connStr;
		private string _name;
		private string _appId;
		private string _usertablename;
		private string _membershiptablename;
		private MembershipCache _membershipcache;
		private UserCache _usercache;
		private ILog _log;

		public Membership()
		{
			_log = LogManager.GetLogger(typeof(Membership));
			_name = "";
			_connName = "";
			_appId = "";
		}

		public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
		{
			_log.Debug("Initialize( name=" + name + " )");

			base.Initialize(name, config);

			_connName = "";
			if (config["connectionStringName"] != null)
				_connName = config["connectionStringName"];

			_name = name;

			_appId = "";
			if (config["applicationId"] != null)
				_appId = config["applicationId"];

			_log.Debug("_appId=" + _appId);

			_usertablename = "aspnet_users";
			_membershiptablename = "aspnet_membership";

			_connStr = "";
			System.Configuration.Configuration config2 = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
			_connStr = config2.ConnectionStrings.ConnectionStrings[_connName].ConnectionString;

			_membershipcache = new MembershipCache(_connStr, _name);
			_usercache = new UserCache(_connStr);

			// config2
		}

		MySqlConnection Connect()
		{
			_log.Debug("Connect( _connName=" + _connName + ", _connStr=" + _connStr + " )");
			MySqlConnection conn = new MySqlConnection(_connStr);
			conn.Open();
			return conn;
		}

		public override bool ChangePassword(string username, string oldPassword, string newPassword)
		{
			bool ret = false;

			_log.Debug("ChangePassword( username=" + username + ", oldPassword=" + oldPassword + ", newPassword=" + newPassword + " )");
			// throw new NotImplementedException();
			string userid = "";
			using (var conn = Connect())
			{
				bool old_ok = false;
				int new_hash_fmt = 1;

				using (var cmd = conn.CreateCommand())
				{
					cmd.CommandText = @"select
						u.UserId, u.Username, m.Password, m.PasswordFormat, m.PasswordSalt, m.IsLockedOut, m.IsApproved
						from " + _usertablename + @" u
						inner join " + _membershiptablename + @" m on m.UserId = u.UserId
						where u.username = @a";
					
					cmd.Parameters.Add(new MySqlParameter("@a", username));
					using (var rdr = cmd.ExecuteReader())
					{
						if (rdr.Read())
						{
							string old_salt = (string)rdr["PasswordSalt"];
							int old_fmt = (int)rdr["PasswordFormat"];
							string correct_hash = (string)rdr["Password"];
							userid = (string)rdr["UserId"];
							new_hash_fmt = old_fmt;
							string test_hash = HashFormsPassword(oldPassword, old_fmt, old_salt);
							_log.Debug("userid=" + userid);
							_log.Debug("db.old_salt=" + old_salt);
							_log.Debug("db.old_fmt=" + old_fmt);
							_log.Debug("db.correct_hash=" + correct_hash);
							_log.Debug("db.test_hash=" + test_hash);
							if (test_hash == correct_hash)
							{
								_log.Debug("hashes match, old password is correct.");
								old_ok = true;
							}
						}
						rdr.Close();
					}
					cmd.Dispose();
				}

				if (old_ok)
				{
					// 
					byte[] data = new byte[0x10];
					new RNGCryptoServiceProvider().GetBytes(data);

					string new_salt = Convert.ToBase64String(data);
					string new_hash = HashFormsPassword(newPassword, new_hash_fmt, new_salt);

					using (var cmd = conn.CreateCommand())
					{
						cmd.CommandText = @"update " + _membershiptablename + @" set PasswordSalt=@s, Password=@p where UserId=@a";
						cmd.Parameters.Add(new MySqlParameter("@p", new_hash));
						cmd.Parameters.Add(new MySqlParameter("@s", new_salt));
						cmd.Parameters.Add(new MySqlParameter("@a", userid));
						cmd.ExecuteNonQuery();
						cmd.Dispose();
						ret = true;
					}
				}

				conn.Close();

			}

			_membershipcache.Flush(userid);

			return ret;
		}

		public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
		{
			_log.Debug("ChangePasswordQuestionAndAnswer( username=" + username + ", password=" + password + ", newPasswordQuestion=" + newPasswordQuestion + ", newPasswordAnswer=" + newPasswordAnswer + " )");
			throw new NotImplementedException();
		}

		public override System.Web.Security.MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out System.Web.Security.MembershipCreateStatus status)
		{
			_log.Debug("CreateUser( username=" + username + ", password=" + password + ", email=" + email + ", passwordQuestion=" + passwordQuestion + ", passwordAnswer=" + passwordAnswer + ", isApproved=" + isApproved + ", " + providerUserKey + " )");

			// TODO: do some more validations here

			status = MembershipCreateStatus.ProviderError;

			string userid = Guid.NewGuid().ToString();

			using (var conn = Connect())
			{
				using (var trans = conn.BeginTransaction())
				{
					using (var cmd = conn.CreateCommand())
					{
						cmd.CommandText = @"insert into " + _usertablename + @" ( ApplicationId, UserId, UserName, LoweredUserName, MobileAlias, IsAnonymous, LastActivityDate )
						values ( @appid, @userid, @username, @username, null, 0, current_timestamp )";
						cmd.Parameters.Add(new MySqlParameter("@appid", _appId));
						cmd.Parameters.Add(new MySqlParameter("@userid", userid));
						cmd.Parameters.Add(new MySqlParameter("@username", username));
						try
						{
							cmd.ExecuteNonQuery();
						}
						catch (Exception z)
						{
							status = MembershipCreateStatus.DuplicateUserName;
						}
						cmd.Dispose();
					}

					int new_hash_fmt = 1;
					byte[] data = new byte[0x10];
					new RNGCryptoServiceProvider().GetBytes(data);
					string new_salt = Convert.ToBase64String(data);
					string new_hash = HashFormsPassword(password, new_hash_fmt, new_salt);

					using (MySqlCommand cmd = conn.CreateCommand())
					{
						cmd.CommandText = @"insert into " + _membershiptablename + @" ( 
							ApplicationId, UserId, 
							Password, PasswordFormat,
							PasswordSalt, MobilePIN,
							Email, LoweredEmail, 
							PasswordQuestion, PasswordAnswer, 
							IsApproved, IsLockedOut, 
							CreateDate, LastLoginDate, LastPasswordChangedDate,
							LastLockoutDate, FailedPasswordAttemptCount, 
							FailedPasswordAttemptWindowStart, FailedPasswordAnswerAttemptCount, 
							FailedPasswordAnswerAttemptWindowStart, Comment )
						values ( 
							@appid, @userid, 
							@passwordhash, @passwordformat, 
							@passwordsalt, null,
							@email, @email, 
							@passwordquestion, @passwordanswer,
							1, 0,
							current_timestamp, '2000-01-01', current_timestamp,
							'2000-01-01', 0, 
							'2000-01-01', 0,
							'2000-01-01', ''
							)";
						cmd.Parameters.Add(new MySqlParameter("@appid", _appId));
						cmd.Parameters.Add(new MySqlParameter("@userid", userid));
						cmd.Parameters.Add(new MySqlParameter("@passwordhash", new_hash));
						cmd.Parameters.Add(new MySqlParameter("@passwordformat", new_hash_fmt));
						cmd.Parameters.Add(new MySqlParameter("@passwordsalt", new_salt));
						cmd.Parameters.Add(new MySqlParameter("@email", email));
						cmd.Parameters.Add(new MySqlParameter("@passwordquestion", passwordQuestion));
						cmd.Parameters.Add(new MySqlParameter("@passwordanswer", passwordAnswer));
						cmd.ExecuteNonQuery();
						cmd.Dispose();
					}

					trans.Commit();
					status = MembershipCreateStatus.Success;
				}
				conn.Close();

			}


			return _membershipcache.GetById(userid);
			// return GetUserByKey(userid, false);
		}

		public override bool DeleteUser(string username, bool deleteAllRelatedData)
		{
			_log.Debug("DeleteUser( username=" + username + ", deleteAllRelatedData=" + deleteAllRelatedData + " )");

			string userid = "";

			using (var conn = Connect())
			{
				using (var cmd = conn.CreateCommand())
				{
					cmd.CommandText = @"select u.userid from " + _usertablename + @" u inner join " + _membershiptablename + @" m on m.UserId = u.UserId where u.username = @a";
					cmd.Parameters.Add(new MySqlParameter("@a", username));
					using (MySqlDataReader rdr = cmd.ExecuteReader())
					{
						if (rdr.Read())
							userid = (string)rdr["userid"];
						rdr.Close();
					}
					cmd.Dispose();
				}

				if (userid != "")
				{
					using (var cmd = conn.CreateCommand())
					{
						cmd.CommandText = @"delete from " + _membershiptablename + @" where UserId = @u";
						cmd.Parameters.Add(new MySqlParameter("@u", userid));
						cmd.ExecuteNonQuery();
					}

					using (var cmd = conn.CreateCommand())
					{
						cmd.CommandText = @"delete from " + _usertablename + @" where UserId = @u";
						cmd.Parameters.Add(new MySqlParameter("@u", userid));
						cmd.ExecuteNonQuery();
					}
				}

				conn.Close();

			}

			_membershipcache.Flush(userid);

			return true;
		}

		public override bool EnablePasswordReset
		{
			get
			{
				_log.Debug("get EnablePasswordReset");
				// throw new NotImplementedException();
				return true;
			}
		}

		public override bool EnablePasswordRetrieval
		{
			get
			{
				_log.Debug("get EnablePasswordRetrieval");
				// throw new NotImplementedException();
				return false;
			}
		}

		public override System.Web.Security.MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
		{
			_log.Debug("FindUsersByEmail( emailToMatch=" + emailToMatch + ", pageIndex=" + pageIndex + ", pageSize=" + pageSize + " )");

			var ret = new MembershipUserCollection();
			/*
			using (MySqlConnection conn = Connect())
			{
				conn.Open();
				using (MySqlCommand cmd = conn.CreateCommand())
				{
					cmd.CommandText = @"select
						u.*, m.*
						from " + _usertablename + @" u
						inner join " + _membershiptablename + @" m on m.UserId = u.UserId
						where u.username = @a";

					cmd.Parameters.Add(new MySqlParameter("@a", username));
					using (MySqlDataReader rdr = cmd.ExecuteReader())
					{
						if (rdr.Read())
						{
							ret = new MyUser(rdr);
						}
						rdr.Close();
					}
					cmd.Dispose();
				}
				conn.Close();
			}
			*/
			totalRecords = 0;
			return ret;
		}

		public override System.Web.Security.MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
		{
			_log.Debug("FindUsersByName( usernameToMatch=" + usernameToMatch + ", pageIndex=" + pageIndex + ", pageSize=" + pageSize + " )");
			var ret = new MembershipUserCollection();
			/*
			using (MySqlConnection conn = Connect())
			{
				conn.Open();
				using (MySqlCommand cmd = conn.CreateCommand())
				{
					cmd.CommandText = @"select
						u.*, m.*
						from " + _usertablename + @" u
						inner join " + _membershiptablename + @" m on m.UserId = u.UserId
						where u.username = @a";

					cmd.Parameters.Add(new MySqlParameter("@a", username));
					using (MySqlDataReader rdr = cmd.ExecuteReader())
					{
						if (rdr.Read())
						{
							ret = new MyUser(rdr);
						}
						rdr.Close();
					}
					cmd.Dispose();
				}
				conn.Close();
			}
			*/
			totalRecords = 0;
			return ret;
		}

		public override System.Web.Security.MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
		{
			_log.Debug("GetAllUsers( pageIndex=" + pageIndex + ", pageSize=" + pageSize + " )");

			var ret = new MembershipUserCollection();
			/*
			using (MySqlConnection conn = Connect())
			{
				conn.Open();
				using (MySqlCommand cmd = conn.CreateCommand())
				{
					cmd.CommandText = @"select
						u.*, m.*
						from " + _usertablename + @" u
						inner join " + _membershiptablename + @" m on m.UserId = u.UserId
						where u.username = @a";

					cmd.Parameters.Add(new MySqlParameter("@a", username));
					using (MySqlDataReader rdr = cmd.ExecuteReader())
					{
						if (rdr.Read())
						{
							ret = new MyUser(rdr);
						}
						rdr.Close();
					}
					cmd.Dispose();
				}
				conn.Close();
			}
			*/
			totalRecords = 0;
			return ret;
		}

		public override int GetNumberOfUsersOnline()
		{
			_log.Debug("GetNumberOfUsersOnline()");
			throw new NotImplementedException();
			// return 0;
		}

		public override string GetPassword(string username, string answer)
		{
			_log.Debug("GetPassword( username=" + username + ", answer=" + answer + " )");
			throw new NotSupportedException();
		}

		public override System.Web.Security.MembershipUser GetUser(string username, bool userIsOnline)
		{
			string userid = _usercache.GetIdByUsername(username);
			return _membershipcache.GetById(userid);
			// return GetUserByKey(userid, userIsOnline);
			/*
						var cached = MembershipCache.Get("byusername-"+username);
						if (cached != null)
							return cached;

						_log.Debug("GetUser( username=" + username + ", userIsOnline=" + userIsOnline + " )");
						MembershipUser ret = null;

						using (MySqlConnection conn = Connect())
						{
							using (MySqlCommand cmd = conn.CreateCommand())
							{
								cmd.CommandText = @"select
									u.*, m.*
									from " + _usertablename + @" u
									inner join " + _membershiptablename + @" m on m.UserId = u.UserId
									where u.username = @a";

								cmd.Parameters.Add(new MySqlParameter("@a", username));
								using (MySqlDataReader rdr = cmd.ExecuteReader())
								{
									if (rdr.Read())
									{
										ret = _innerGetUser(rdr);
									}
									rdr.Close();
								}
								cmd.Dispose();
							}
							conn.Close();
						}

						if (ret != null)
							MembershipCache.Store("byusername-" + username, ret);

		
						return ret;*/
		}

		//private MembershipUser GetUserByKey(object providerUserKey, bool userIsOnline)
		//{
		//    return _membershipcache.GetById(providerUserKey.ToString());
		//    /*

		//    var cached = MembershipCache.Get("bykey-" + providerUserKey.ToString());
		//    if (cached != null)
		//        return cached;

		//    _log.Debug("GetUser( providerUserKey=" + providerUserKey + ", userIsOnline=" + userIsOnline + " )");
		//    MembershipUser ret = null;

		//    using (MySqlConnection conn = Connect())
		//    {
		//        using (MySqlCommand cmd = conn.CreateCommand())
		//        {
		//            cmd.CommandText = @"select u.*, m.*
		//                from " + _usertablename + @" u
		//                inner join " + _membershiptablename + @" m on m.UserId = u.UserId
		//                where u.userid = @a";

		//            cmd.Parameters.Add(new MySqlParameter("@a", providerUserKey.ToString()));
		//            using (MySqlDataReader rdr = cmd.ExecuteReader())
		//            {
		//                if (rdr.Read())
		//                {
		//                    ret = _innerGetUser(rdr);
		//                }
		//                rdr.Close();
		//            }
		//            cmd.Dispose();
		//        }
		//        conn.Close();
		//    }

		//    if( ret != null )
		//        MembershipCache.Store("bykey-"+providerUserKey.ToString(), ret);

		//    return ret;*/
		//}

		public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
		{
			return _membershipcache.GetById(providerUserKey.ToString());
			// return GetUserByKey(providerUserKey, userIsOnline);
		}

		public override string GetUserNameByEmail(string email)
		{
			_log.Debug("GetUserNameByEmail( email=" + email + " )");

			if (string.IsNullOrEmpty(email))
				return null;

			string ret = _usercache.GetUsernameByEmail(email);

			if (string.IsNullOrEmpty(ret))
				return null;

			return ret;

			/*
			string ret = "";
			using (MySqlConnection conn = Connect())
			{
				using (MySqlCommand cmd = conn.CreateCommand())
				{
					cmd.CommandText = @"select u.username
						from " + _usertablename + @" u
						inner join " + _membershiptablename + @" m on m.UserId = u.UserId
						where m.email = @a";

					cmd.Parameters.Add(new MySqlParameter("@a", email));
					using (MySqlDataReader rdr = cmd.ExecuteReader())
					{
						if (rdr.Read())
						{
							ret = (string)rdr["username"];
						}
						rdr.Close();
					}
					cmd.Dispose();
				}
				conn.Close();
			}

			_log.Debug("username=" + ret);

			if (string.IsNullOrEmpty(ret))
				return null;

			return ret;*/
		}

		public override int MaxInvalidPasswordAttempts
		{
			get
			{
				_log.Debug("get MaxInvalidPasswordAttempts");
				//	throw new NotImplementedException(); 
				return 3;
			}
		}

		public override int MinRequiredNonAlphanumericCharacters
		{
			get
			{
				_log.Debug("get MinRequiredNonAlphanumericCharacters");
				return 0;
				//	throw new NotImplementedException(); 
			}
		}

		public override int MinRequiredPasswordLength
		{
			get
			{
				_log.Debug("get MinRequiredPasswordLength");
				return 5;
				//	throw new NotImplementedException(); 
			}
		}

		public override int PasswordAttemptWindow
		{
			get
			{
				_log.Debug("get PasswordAttemptWindow");
				return 5;
				// throw new NotImplementedException();
			}
		}

		public override System.Web.Security.MembershipPasswordFormat PasswordFormat
		{
			get
			{
				_log.Debug("get PasswordFormat");
				// throw new NotImplementedException(); 
				return MembershipPasswordFormat.Hashed;
			}
		}


		public override string PasswordStrengthRegularExpression
		{
			get
			{
				_log.Debug("get PasswordStrengthRegularExpression");
				// base.con
				// throw new NotImplementedException();
				return "[a-z0-9]{6,}";
			}
		}

		public override bool RequiresQuestionAndAnswer
		{
			get
			{
				_log.Debug("get RequiresQuestionAndAnswer");
				return false;
				// throw new NotImplementedException(); 
			}
		}

		public override bool RequiresUniqueEmail
		{
			get
			{
				_log.Debug("get RequiresUniqueEmail");
				return true;
				// throw new NotImplementedException(); 
			}
		}

		public override string ResetPassword(string username, string answer)
		{
			_log.Debug("ResetPassword( username=" + username + ", answer=" + answer + " )");
			//	throw new NotImplementedException();

			string newpass = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 8);
			_log.Debug("newpass=" + newpass);

			string userid = "";

			using (var conn = Connect())
			{
				int new_hash_fmt = 1;

				using (var cmd = conn.CreateCommand())
				{
					cmd.CommandText = @"select
						u.userid, m.passwordanswer, m.passwordformat, m.passwordsalt
						from " + _usertablename + @" u
						inner join " + _membershiptablename + @" m on m.UserId = u.UserId
						where u.username = @a";

					// 

					cmd.Parameters.Add(new MySqlParameter("@a", username));
					using (var rdr = cmd.ExecuteReader())
					{
						if (rdr.Read())
						{
							userid = (string)rdr["userid"];
							new_hash_fmt = (int)rdr["passwordformat"];
						}
						rdr.Close();
					}
					cmd.Dispose();
				}

				_log.Debug("userid=" + userid);
				if (!string.IsNullOrEmpty(userid))
				{

					byte[] data = new byte[0x10];
					new RNGCryptoServiceProvider().GetBytes(data);
					string new_salt = Convert.ToBase64String(data);
					string new_hash = HashFormsPassword(newpass, new_hash_fmt, new_salt);

					_log.Debug("new_salt=" + new_salt);
					_log.Debug("new_hash=" + new_hash);

					using (var cmd = conn.CreateCommand())
					{
						cmd.CommandText = @"update " + _membershiptablename + @" set Password=@p, PasswordSalt=@s where userid = @a";

						cmd.Parameters.Add(new MySqlParameter("@p", new_hash));
						cmd.Parameters.Add(new MySqlParameter("@s", new_salt));
						cmd.Parameters.Add(new MySqlParameter("@a", userid));
						cmd.ExecuteNonQuery();
						cmd.Dispose();
					}
				}

				conn.Close();
			}

			_membershipcache.Flush(userid);

			return newpass;
		}

		public override bool UnlockUser(string userName)
		{
			bool ret = false;
			string userid = "";
			bool was_locked_out = false;

			using (var conn = Connect())
			{
				using (var cmd = conn.CreateCommand())
				{
					cmd.CommandText = @"select
						u.UserId, m.IsLockedOut
						from " + _usertablename + @" u
						inner join " + _membershiptablename + @" m on m.UserId = u.UserId
						where u.username = @a";

					cmd.Parameters.Add(new MySqlParameter("@a", userName));
					using (var rdr = cmd.ExecuteReader())
					{
						if (rdr.Read())
						{
							userid = (string)rdr["UserId"];
							int lockout = 0;
							int.TryParse(rdr["IsLockedOut"].ToString(), out lockout);
							_log.Debug("db.userid=" + userid);
							_log.Debug("db.lockout=" + lockout);

							if (lockout == 1)
							{
								was_locked_out = true;
							}
						}
						rdr.Close();
					}
					cmd.Dispose();
				}

				if (was_locked_out)
				{
					using (var cmd = conn.CreateCommand())
					{
						cmd.CommandText = @"update " + _membershiptablename + @" set IsLockedOut=0 where UserId=@a";
						cmd.Parameters.Add(new MySqlParameter("@a", userid));
						cmd.ExecuteNonQuery();
						cmd.Dispose();
					}
				}

				conn.Close();
			}

			_membershipcache.Flush(userid);

			return was_locked_out;
			// _log.Debug("UnlockUser( userName=" + userName + " )");
			// throw new NotImplementedException();
		}

		public override void UpdateUser(System.Web.Security.MembershipUser user)
		{
			_log.Debug("UpdateUser( user=" + user + " )");

			if (user != null)
				_membershipcache.Flush(user.ProviderUserKey.ToString());

			throw new NotImplementedException();
		}

		internal string HashFormsPassword(string pass, int passwordFormat, string salt)
		{
			if (passwordFormat == 0)
				return pass;

			byte[] bytes = Encoding.Unicode.GetBytes(pass);
			byte[] src = Convert.FromBase64String(salt);
			byte[] dst = new byte[src.Length + bytes.Length];
			byte[] inArray = null;
			Buffer.BlockCopy(src, 0, dst, 0, src.Length);
			Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length);
			HashAlgorithm algorithm = null;

			switch ((int)passwordFormat)
			{
				case (int)FormsAuthPasswordFormat.SHA1:
					algorithm = HashAlgorithm.Create("sha1");
					break;

				case (int)FormsAuthPasswordFormat.MD5:
					algorithm = HashAlgorithm.Create("md5");
					break;
			}

			inArray = algorithm.ComputeHash(dst);

			return Convert.ToBase64String(inArray);
		}


		public override bool ValidateUser(string username, string password)
		{
			bool ret = false;

			_log.Debug("ValidateUser( username=" + username + ", password=" + password + " )");

			using (var conn = Connect())
			{
				using (var cmd = conn.CreateCommand())
				{
					cmd.CommandText = @"select
						u.UserId, u.Username, m.Password, m.PasswordFormat, m.PasswordSalt, m.IsLockedOut, m.IsApproved
						from " + _usertablename + @" u
						inner join " + _membershiptablename + @" m on m.UserId = u.UserId
						where u.username = @a";

					cmd.Parameters.Add(new MySqlParameter("@a", username));
					using (var rdr = cmd.ExecuteReader())
					{
						if (rdr.Read())
						{
							string salt = (string)rdr["PasswordSalt"];
							int fmt = (int)rdr["PasswordFormat"];
							int lockout = 0;
							int.TryParse(rdr["IsLockedOut"].ToString(), out lockout);
							int approved = 0;
							int.TryParse(rdr["IsApproved"].ToString(), out approved);
							string correct_hash = (string)rdr["Password"];
							string userid = (string)rdr["UserId"];

							string test_hash = HashFormsPassword(password, fmt, salt);// password;

							_log.Debug("db.userid=" + userid);
							_log.Debug("db.lockout=" + lockout);
							_log.Debug("db.approved=" + approved);
							_log.Debug("db.salt=" + salt);
							_log.Debug("db.fmt=" + fmt);
							_log.Debug("db.correct_hash=" + correct_hash);
							_log.Debug("db.test_hash=" + test_hash);

							if (approved == 1 &&
								lockout == 0 &&
								test_hash == correct_hash)
							{
								_log.Debug("hashes match, successful login.");
								ret = true;
							}
						}
						rdr.Close();
					}
					cmd.Dispose();
				}
				conn.Close();
			}
			_log.Debug("ValidateUser = " + ret);
			return ret;
		}







	}
}
